#!/bin/bash

# A script to import Containerd images from a compressed tarball created by the export script.

# Define variables
OUTPUT_DIR="./"
BACKUP_FILE="k8s_images.tar.gz"
TEMP_DIR="$OUTPUT_DIR/images_import"
NAMESPACE="k8s.io"

# --- Functions for error handling and cleanup ---
# This function will be called if the script exits unexpectedly.
cleanup() {
    echo "Cleaning up temporary directory: $TEMP_DIR"
    rm -r "$TEMP_DIR" 2>/dev/null
    echo "Exiting."
}

# Trap signals (e.g., Ctrl+C) to ensure cleanup runs.
trap cleanup INT TERM

# --- Script execution starts here ---

# Check if the required backup file exists
if [ ! -f "$OUTPUT_DIR/$BACKUP_FILE" ]; then
    echo "Error: Backup file not found at $OUTPUT_DIR/$BACKUP_FILE"
    echo "Please ensure the file exists and the date in the filename is correct."
    exit 1
fi

# Create a temporary directory for image extraction
echo "Creating temporary directory: $TEMP_DIR"
mkdir -p "$TEMP_DIR" || { echo "Failed to create directory. Exiting."; exit 1; }

# Decompress the main tarball and extract the individual image tars
echo "Decompressing and extracting the main tarball..."
tar -xf "$OUTPUT_DIR/$BACKUP_FILE" -C "$TEMP_DIR" || {
    echo "Failed to extract tarball. Exiting."
    cleanup
    exit 1
}

# Check if any images were successfully extracted
if [ -z "$(ls -A "$TEMP_DIR" 2>/dev/null)" ]; then
    echo "No images were successfully extracted from the tarball. Exiting."
    cleanup
    exit 1
fi

# Import each individual image tar into the Containerd image store
echo "Importing images into the '$NAMESPACE' namespace..."
for image_file in "$TEMP_DIR"/*.tar; do
    echo "Importing: $image_file"
    # The ctr command will handle the import of a single image tar.
    # The -n flag specifies the namespace.
    sudo ctr -n "$NAMESPACE" images import "$image_file" || {
        echo "Warning: Failed to import image from $image_file. Continuing to next image."
    }
done

# Clean up the temporary directory
echo "Image import process complete!"
cleanup

# Verify images
echo "Verifying images with crictl..."
sudo crictl images

